package com.jfinal.weixin.weixinbot;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.PathKit;

import cn.zhouyafeng.itchat4j.Wechat;
import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.api.WechatTools;
import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import cn.zhouyafeng.itchat4j.utils.MyHttpClient;
import cn.zhouyafeng.itchat4j.utils.enums.MsgTypeEnum;
import cn.zhouyafeng.itchat4j.utils.tools.DownloadTools;

/**
 * 简单示例程序，收到文本信息自动回复原信息，收到图片、语音、小视频后根据路径自动保存
 * 
 * @author https://github.com/yaphone
 * @date 创建时间：2017年4月25日 上午12:18:09
 * @version 1.0
 *
 */
public class WeixinbotDemo implements IMsgHandlerFace {
	MyHttpClient myHttpClient = Core.getInstance().getMyHttpClient();
	String apiKey = "5593f526f892ccbbcf0d7f4b1aba9002"; // 这里是我申请的图灵机器人API接口，每天只能5000次调用，建议自己去申请一个，免费的:)

	Wechat wechat = null;
	
	static WeixinbotDemo instance = null;
	
	public static WeixinbotDemo getInstance() {
		synchronized (WeixinbotDemo.class) {
			if (instance == null) {
				instance = new WeixinbotDemo();
			}
			return instance;
		}
	}
	
	public WeixinbotDemo() {
		wechat = new Wechat(this); // 【注入】
	}
	
	public String createQR() {
		String qrPath = PathKit.getWebRootPath() + "/upload/ghy/login"; // 保存登陆二维码图片的路径
		wechat.createQR(qrPath);
		return qrPath;
	}
	
	public boolean weLoginOneTime() {
		return wechat.weLoginOneTime();
	}
	
	public void startMsg() {
		wechat.start(); 
		
	}
	
	public static void main(String[] args) {
		weStart();
	}
	
	public static String weStart() {
		String qrPath = PathKit.getWebRootPath() + "/upload/ghy/login"; // 保存登陆二维码图片的路径
		IMsgHandlerFace msgHandler = new WeixinbotDemo(); // 实现IMsgHandlerFace接口的类
		Wechat wechat = new Wechat(msgHandler); // 【注入】
		wechat.login(qrPath);
		wechat.start(); // 启动服务，会在qrPath下生成一张二维码图片，扫描即可登陆，注意，二维码图片如果超过一定时间未扫描会过期，过期时会自动更新，所以你可能需要重新打开图片
		
		return qrPath;
	}
	
	private void insertMsg(JSONObject m) {
		
		JSONObject userInfo = null;
		WeixinMsgModel msgModel = new WeixinMsgModel();
		
//		boolean isGroupMsg = m.getBoolean("groupMsg");
//		msgModel.setCreateTime(m.getLongValue("CreateTime")+"");
//		msgModel.setContent(m.getString("Content"));
//		msgModel.setFileUrl(m.getString("FileUrl"));
//		msgModel.setText(m.getString("Text"));
//		msgModel.setMsgType(m.getInteger("MsgType"));
//		msgModel.setType(m.getString("Type"));
//		msgModel.setFromUserName(m.getString("FromUserName"));
//		msgModel.setToUserName(m.getString("ToUserName"));
//		msgModel.setMsgId(m.getString("MsgId"));
//		msgModel.setNewMsgId(m.getString("NewMsgId"));
//		msgModel.setGroupMsg(isGroupMsg+"");
//		msgModel.setStatus(m.getInteger("Status")+"");
//		msgModel.setOriginalMsg(m.toJSONString());
		
		msgModel.set("createTime", m.getLongValue("CreateTime"));
		msgModel.set("content", m.getString("Content"));
		msgModel.set("fileUrl", m.getString("FileUrl"));
		msgModel.set("text", m.getString("Text"));
		msgModel.set("msgType", m.getInteger("MsgType"));
		msgModel.set("type", m.getString("Type"));
		msgModel.set("fromUserName", m.getString("FromUserName"));
		msgModel.set("toUserName", m.getString("ToUserName"));
		msgModel.set("msgId", m.getString("MsgId"));
		msgModel.set("newMsgId", m.getString("NewMsgId"));
		msgModel.set("groupMsg", m.getBoolean("groupMsg"));
		msgModel.set("status", m.getInteger("Status"));
		msgModel.set("originalMsg", m.toJSONString());
		
		userInfo = WechatTools.getUserInfoByUserName(m.getString("FromUserName"));
		
		if (userInfo != null) {
//			msgModel.setNickName(userInfo.getString("NickName"));
//			msgModel.setRemarkName(userInfo.getString("RemarkName"));
			msgModel.set("nickName", m.getString("NickName"));
			msgModel.set("remarkName", m.getString("RemarkName"));
		}
		msgModel.save();
		
	}
	
	@Override
	public String textMsgHandle(JSONObject msg) {
		insertMsg(msg);
//		String userId = msg.getString("FromUserName");
		String text = msg.getString("Text"); // 发送文本消息，也可调用MessageTools.sendFileMsgByUserId(userId,text);
		String sourceText = "";
		String result = null;
		if (!msg.getBoolean("groupMsg")) { // 群消息不处理
			sourceText = text;
		} else {
			
			sourceText = text;
			
			if (text.contains("@范羊")) {
				sourceText = text.replaceAll("@范羊", "");
			} else if (text.contains("@范羊-技术好")) {
				sourceText = text.replaceAll("@范羊-技术好", "");
			}
			if (text.contains("@郑明青－技术部")) {
				MessageTools.sendMsgByNickName("群消息提醒：\""+text.replaceAll("@郑明青－技术部", "")+"\"", "cosmo");
				MessageTools.sendMsgById("别急，已微信通知@郑明青", msg.getString("FromUserName"));
			}
			if (text.contains("@所有人")) {
				sourceText = text.replaceAll("@所有人", "");
			}
			if (text.contains("机器人")) {
				sourceText = text;
			}
			
		}
		sourceText = sourceText.trim();
		if (!"".equals(sourceText)) {
			result = getByTuling(sourceText);
		} else {
			if (text.contains("@范羊") || text.contains("@范羊-技术好")) {
				result = "要跟我说话就说完话马上@我！！！";
			}
			
		}
		
		if (Core.getInstance().getAutoReply().get(msg.getString("FromUserName")) != null && !Core.getInstance().getAutoReply().get(msg.getString("FromUserName"))) {
			result = null;
		}
		return result;
	}

	/**
	 * 获取图灵智能问答结果
	 * @param sourceText
	 * @return
	 */
	private String getByTuling(String sourceText) {
		String result = "";
		String url = "http://www.tuling123.com/openapi/api";
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("key", apiKey);
		paramMap.put("info", sourceText);
		paramMap.put("userid", "123456");
		String paramStr = JSON.toJSONString(paramMap);
		try {
			HttpEntity entity = myHttpClient.doPost(url, paramStr);
			result = EntityUtils.toString(entity, "UTF-8");
			JSONObject obj = JSON.parseObject(result);
			if (obj.getString("code").equals("100000")) {
				result = obj.getString("text");
			} else {
				result = "你说的我不太懂！！！";
			}
		} catch (Exception e) {
			
		}
		return result;
	}
	
	@Override
	public String picMsgHandle(JSONObject msg) {
		String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());// 这里使用收到图片的时间作为文件名
		String picPath = "E://itchat4j/pic" + File.separator + fileName + ".jpg"; // 调用此方法来保存图片
		DownloadTools.getDownloadFn(msg, MsgTypeEnum.PIC.getType(), picPath); // 保存图片的路径
		msg.put("FileUrl", picPath);
		insertMsg(msg);
		return null;
	}

	@Override
	public String voiceMsgHandle(JSONObject msg) {
		String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
		String voicePath = "E://itchat4j/voice" + File.separator + fileName + ".mp3";
		DownloadTools.getDownloadFn(msg, MsgTypeEnum.VOICE.getType(), voicePath);
		msg.put("FileUrl", voicePath);
		insertMsg(msg);
		return null;
	}

	@Override
	public String viedoMsgHandle(JSONObject msg) {
		String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
		String viedoPath = "E://itchat4j/viedo" + File.separator + fileName + ".mp4";
		DownloadTools.getDownloadFn(msg, MsgTypeEnum.VIEDO.getType(), viedoPath);
		msg.put("FileUrl", viedoPath);
		insertMsg(msg);
		return null;
	}

	@Override
	public String nameCardMsgHandle(JSONObject msg) {
//		return "收到名片消息";
		return null;
	}

	@Override
	public String recalledMsgHandle(JSONObject msg) {
		String result = null;
		WeixinMsgModel msgModel = new WeixinMsgModel();
		try {
			String ss = msg.getString("Content");
			Pattern p=Pattern.compile("&lt;msgid&gt;(\\w+)&lt;/msgid&gt;");
		    Matcher m=p.matcher(ss);
		    String msgId = "";
		    if (m.find()) {
		    	msgId = m.group(1);
		    }
		    String replacemsg = "";
		    Pattern p2=Pattern.compile("&lt;replacemsg&gt;&lt;!\\[CDATA\\[(?<text>[^\\]]*)\\]\\]&gt;&lt;/replacemsg&gt;");
		    Matcher m2=p2.matcher(ss);
		    if (m2.find()) {
		    	replacemsg = m2.group(1);
		    }
			List<WeixinMsgModel> msgs = msgModel.findBySql("select * from wx_msg where msgId = '"+msgId+"'");
			if (msgs != null && msgs.size()>0) {
				WeixinMsgModel msgM = msgs.get(0);
				String text = "";
				if ("".equals(msgM.get("text")) || "null".equals(msgM.get("text")) || null == msgM.get("text")) {
					
				} else {
					text = "\""+msgM.get("text")+"\"";
				}
				if ("".equals(replacemsg)) {
					result = "您撤回了消息：" + text;
				} else {
					result = replacemsg + "：" + text;
				}
				//调用发送文本消息接口
				MessageTools.sendMsgById(result, msg.getString("FromUserName"));
				if (msgM.getStr("type").equals(MsgTypeEnum.TEXT.getType())) {
					
				} else if (msgM.getStr("type").equals(MsgTypeEnum.PIC.getType())) {
					MessageTools.sendPicMsgByUserId(msg.getString("FromUserName"), msgM.getStr("fileUrl"));
				} else if (msgM.getStr("type").equals(MsgTypeEnum.VOICE.getType())) {
					MessageTools.sendFileMsgByUserId(msg.getString("FromUserName"), msgM.getStr("fileUrl"));
				} else if (msgM.getStr("type").equals(MsgTypeEnum.VIEDO.getType())) {
					MessageTools.sendFileMsgByUserId(msg.getString("FromUserName"), msgM.getStr("fileUrl"));
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
